package com.example.springcloudeurekaserverproducer.AOP;

import com.example.springcloudeurekaserverproducer.controller.BaseBean;
import org.apache.ibatis.transaction.Transaction;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ControllerAOP  {
	private static final Logger logger = LoggerFactory.getLogger(ControllerAOP.class);


	@Pointcut("execution(public com.example.springcloudeurekaserverproducer.controller.BaseBean *(..))")
	public void controllerMethod() {
	}

	@Around("controllerMethod()")
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		BaseBean<?> result;
		try {
			result = (BaseBean<?>) pjp.proceed();
			logger.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
		} catch (Throwable e) {
			result = handlerException(pjp, e);

		}
		return result;
	}

	private BaseBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		BaseBean<?> result = new BaseBean();
		// 已知异常
		if (e instanceof Exception) {
			result.setMsg(e.getLocalizedMessage());
			result.setCode(BaseBean.FAIL);
		}
		else {
			logger.error(pjp.getSignature() + " error ", e);
//			TODO 未知的异常
			result.setMsg(e.toString());
			result.setCode(BaseBean.FAIL);
		}
		return result;
	}
	}

